/*
    RoleCall provides a web service that web applications can use to find 
    the roles associated with a user that has been authenticated via OpenID. 
    Also provides a web-based user interface to manage the user roles 
    associated with partner web applications.
    
    Development of this software was supported in part by the David and Lucile 
    Packard Foundation and by the the Office Of Naval Research (ONR) 
     
    Copyright (c) 2012, 
    Monterey Bay Aquarium Research Institute - MBARI ( www.mbari.org )
    Michael Godin ( mikegodin AT users DOT sourceforge DOT net )

    RoleCall is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    RoleCall is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar (see the file COPYING.GPL).  If not, see 
    <http://www.gnu.org/licenses/>.  
*/

package rolecall.gwt.client;

import java.util.Date;
import java.util.List;

import org.mbari.rolecall.model.Provider;
import org.mbari.rolecall.model.Status;
import org.mbari.rolecall.model.User;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class Partner implements EntryPoint {

    public static Date nextYear() {
        return new Date((new Date()).getTime() + 86400L * 1000L * 365L);
    }

    private CheckBox keepLoginBox = null;

    private DialogBox loginDialog;

    private final PartnerServiceAsync service = GWT
            .create(PartnerService.class);

    Status status;

    User user;

    private void constructLoginDialog() {
        loginDialog = new DialogBox(false, true);
        loginDialog.setText("Login via:");

        final VerticalPanel vPanel = new VerticalPanel();
        loginDialog.add(vPanel);

        keepLoginBox = new CheckBox("Keep me logged in.");
        String keepLoginStr = Cookies.getCookie("openid_identifier");
        keepLoginBox
                .setValue(null == keepLoginStr || keepLoginStr.length() > 0);
        vPanel.add(keepLoginBox);

        service.getProviders(new AsyncCallback<List<Provider>>() {

            @Override
            public void onFailure(Throwable caught) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSuccess(List<Provider> result) {
                if (null != result) {
                    for (final Provider provider : result) {
                        vPanel.add(new Button(
                                "<img style='width:16px;height:16px' src='"
                                        + provider.getFaviconURL() + "'/> <b>"
                                        + provider.getName() + "</b>",
                                new ClickHandler() {

                                    @Override
                                    public void onClick(ClickEvent event) {
                                        loginOpenId(provider.getUrl(),
                                                provider.getPrompt());
                                    }
                                }));
                    }
                }
            }
        });
    }

    public void handleStatus(Status status) {
        if (null == this.status) {
            user = status.getUser();
            if (null == user) {
                Cookies.removeCookie("openid_identifier", "/");
                RootPanel.get().add(new Button("Login", new ClickHandler() {
                    @Override
                    public void onClick(ClickEvent event) {
                        showLoginDialog();
                    }
                }));
            } else {
                RootPanel.get().add(
                        new Label("Welcome " + user.getName() + " <"
                                + user.getEmail() + "> (" + user.getOpenId()
                                + ")"));
                RootPanel.get().add(
                        new Label("Roles: "
                                + (null == user.getRoles() ? "none." : user
                                        .getRoles())));
                RootPanel.get().add(new Button("Logout", new ClickHandler() {
                    @Override
                    public void onClick(ClickEvent event) {
                        logout();
                    }
                }));
            }
        }
        this.status = status;
    }

    private void loginOpenId(String openIdUrl, String prompt) {

        if (null != prompt && prompt.length() > 0) {
            String promptResult = Window.prompt(prompt, "");
            if (null != promptResult) {
                openIdUrl = openIdUrl.replace("%s", promptResult);
            } else {
                return;
            }
        }

        if (null != keepLoginBox && keepLoginBox.getValue()) {
            Cookies.setCookie("openid_identifier", openIdUrl, nextYear(), null,
                    "/", false);
        }

        FormPanel form = new FormPanel("_self");
        form.setMethod(FormPanel.METHOD_POST);
        form.setAction(Window.Location.getHref());
        RootPanel.get().add(form);
        form.add(new Hidden("openid_identifier", openIdUrl));
        form.submit();

    }

    protected void logout() {
        Cookies.removeCookie("openid_identifier", "/");
        FormPanel form = new FormPanel("_self");
        form.setMethod(FormPanel.METHOD_POST);
        form.setAction(Window.Location.getHref());
        RootPanel.get().add(form);
        form.add(new Hidden("logout", "true"));
        form.submit();
    }

    public void onModuleLoad() {

        service.getStatus(new AsyncCallback<Status>() {
            @Override
            public void onFailure(Throwable caught) {
                reportError("Error getting user", caught);
            }

            @Override
            public void onSuccess(Status status) {
                handleStatus(status);
            }
        });

    }

    public void reportError(String message, Throwable caught) {
        Window.alert(message + " due to " + caught);
    }

    protected void showLoginDialog() {
        if (null == loginDialog) {
            constructLoginDialog();
        }
        loginDialog.center();
    }
}
